<?php

namespace Portal\Controller;
use Common\Controller\HomebaseController; 
/**
 * 首页
 */
class AuthLoginController extends HomebaseController{

    protected static $appId;
    protected static $appSecret;
    //注意 如果此处的的商户秘钥需要修改的话，同步修改同级目录下NotifyController.class.php第9行的key
    protected static $key;//商户支付秘钥key
    
    public function __construct() {
        parent::__construct();

        self::$appId     = C('APPID');
        self::$appSecret = C('APPSECRET');
        self::$key       = C('KEY');
         
        if(!$_SESSION['wx_user_id'] || !$_SESSION['openid']){
            $this->wechatLogin();
        }
    }
 
   /**
    * 微信授权登陆
    **/
    private function wechatLogin(){
        $code   = isset($_GET['code']) ? $_GET['code'] : $this->getCode();//获取code
        if ($code) {
            $user_wx_info = $this->getUserWechatInfo($code);//由code获取用户微信信息   
          
           
            if(!$user_info = M('Wx_user')->where('openid = "'.$user_wx_info['openid'].'"')->find()){
                
                //如果是新用户，将用户的微信信息插入数据库，
                $add_user_info['openid']      = $user_wx_info['openid'];   //用户微信身份唯一标识
                $add_user_info['nick_name']   = $user_wx_info['nickname']; //用户微信名
                $add_user_info['gender']      = $user_wx_info['sex'] == '1' ? '男':'女'; //用户微信性别
                $add_user_info['head_img']    = $user_wx_info['headimgurl']; //用户微信头像
                $add_user_info['reg_date']    = time();
                //插入保存登陆信息
                if ($res = M('Wx_user')->add($add_user_info)) {
                    session('wx_user_id',$res);
                    session('openid',$add_user_info['openid']);
                }
            }else{
              
                session('wx_user_id',$user_info['id']);
                session('openid',$user_info['openid']);
            }
        }
        
    }

    //微信获取code
    private function getCode(){
        //触发微信返回code码
        $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
        $url = $this->__CreateOauthUrlForCode($baseUrl);
        header("Location: $url");
        exit();
    }
    //获取用户的基本信息
    private function getUserWechatInfo($code){
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.self::$appId.'&secret='.self::$appSecret.'&code='.$code.'&grant_type=authorization_code';
      
        $ch            = curl_init();

        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        
        $res = curl_exec($ch);
        curl_close($ch);

        $json_obj = json_decode($res,true);

        //根据openid和access_token查询用户信息
        $access_token = $json_obj['access_token'];
        $openid       = $json_obj['openid'];

        $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
      
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        $res = curl_exec($ch);
        curl_close($ch);
        $user_obj = json_decode($res,true);
        return $user_obj;
    }

    /**
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl){
        $urlObj["appid"]         = self::$appId;
        $urlObj["redirect_uri"]  = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"]         = "snsapi_userinfo";
        $urlObj["state"]         = "STATE"."#wechat_redirect";
        $bizString               = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
  
    /**
     *
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj){
        $buff = "";
        foreach ($urlObj as $k => $v){
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

}


